<?php
//后台用户model文件
class AdminUserModel extends Model {
	public function __construct(){
		parent::__construct();
	}
	function fineUser($username , $password){
		$password = md5($password);
		$info = M("Admin_user")->where("username='{$username}' and passwd = '{$password}' ")->find();
		if($info){
			if(!$info['status']){
				return array('status' => 0 , 'message'=>'此用户已经被禁用');
			}
		}else{
			return array('status' => 0 , 'message'=>'用户不存在,或者密码错误');
		}
		return array('status' => 1 , 'message'=>'success' , 'info'=>$info) ;
	}
	//设置后台用户的登录状态
	public function setUserCookie($uid){
		$info = M("Admin_user")->where("id = '{$uid}' ")->find();
		if(!$info){
			return array('status' => 0 , 'message'=>'用户不存在');
		}
		if($info['super_admin'] == 1 ){
			$info['group_name'] = "管理员";
		}else{
			if($info['gid'] <= 0 ){
				return array('status' => 0 , 'message'=>"用户{$info['username']}没有加入任何的组不运行操作");
			}
			$roleData = M("Admin_role")->where("id = '{$info['gid']}' ")->find();
			if($roleData['status'] == 0 ){
				return array('status' => 0 , 'message'=>"用户{$info['username']}你所在的组{$roleData['rolename']}已经被关闭");
			}
			$info['group_name'] = $roleData['rolename'];
		}
		$data_string = serialize($info) ;
		$data_string = auth_code($data_string , "ENCODE" , C("s_key"));
		cookie('admin_auth',$data_string,array('expire'=>C("cookie_expire"),'prefix'=>C("cookie_prefix")));
		//写入登陆日志记录表里面
		##############################################################################
		$data_login_log = array(
		'username'=>$info['username'],
		'logintime'=>date("Y-m-d H:i:s",time()),
		'ip'=>get_client_ip(),//登陆ip地址
		);
		M("Adminloginlog")->add($data_login_log);
		//写入操作日志表里面
		write_action_log("login_sql",getModuleAction(),$info['username'],get_client_ip(),1,"用户{$info['username']}登录成功");
		//修改用户的登录次数
		$sql = "UPDATE ".C("DB_PREFIX")."admin_user SET login_num = login_num + 1 where id = '{$uid}' ";
	
		M()->query($sql);
		//
		$logintime = time();
		$session_id = $data_string;
		$sql_session = "insert into `".C("DB_PREFIX")."admin_session`(username , time , session_id ,  userid)values('{$info['username']}','{$logintime}' , '{$session_id}' ,'{$info['id']}' ) ON DUPLICATE KEY UPDATE session_id = '{$session_id}' " ; 
		$this->db->query($sql_session) ;
		return array('status' => 1 , 'message'=>'success');
	}
}
